package com.centaline.androidsalesblog.activities.newest;

import android.text.TextUtils;

import com.android.volley.VolleyError;
import com.baidu.location.BDLocation;
import com.baidu.location.LocationClient;
import com.baidu.mapapi.model.LatLng;
import com.centaline.androidsalesblog.R;
import com.centaline.androidsalesblog.api.newest.NewEstListApi;
import com.centaline.androidsalesblog.application.MyLocation;
import com.centaline.androidsalesblog.base.BaseActivity;
import com.centaline.androidsalesblog.constants.AppConstant;
import com.centaline.androidsalesblog.constants.CommonConstant;
import com.centaline.androidsalesblog.constants.ExtraConstant;
import com.centaline.androidsalesblog.fragments.list.NewEstListFragment;
import com.centaline.androidsalesblog.iml.DropCompleteListener;
import com.centaline.androidsalesblog.iml.RefreshListener;
import com.centaline.androidsalesblog.model.businissobject.DropBo;
import com.centaline.androidsalesblog.model.responseobject.NewEstListRo;
import com.centaline.androidsalesblog.rx.database.NewEstSearchDataFunc1;
import com.centaline.androidsalesblog.rx.database.RxDataBase;
import com.centaline.androidsalesblog.rx.map.RxMap;
import com.centaline.androidsalesblog.utils.DateUtil;
import com.centaline.androidsalesblog.utils.DropUtil;
import com.centaline.androidsalesblog.widgets.dropdown.DoubleDrop;
import com.centaline.androidsalesblog.widgets.dropdown.DropDownView;
import com.centaline.androidsalesblog.widgets.dropdown.MoreDrop;
import com.centaline.androidsalesblog.widgets.dropdown.SalePriceDrop;
import com.centaline.androidsalesblog.widgets.dropdown.SingleDrop;
import com.centanet.framework.interfaces.IResponseListener;
import com.trello.rxlifecycle.ActivityEvent;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;

import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.functions.Func2;
import rx.functions.Func4;
import rx.schedulers.Schedulers;

/**
 * 周边新盘推荐
 * Created by guilin on 16/3/24.
 */
public class NearbyNewEstListActivity extends BaseActivity {

    private DropDownView dropDownView;
    private NewEstListFragment newEstListFragment;

    private DoubleDrop doubleDrop;
    private SalePriceDrop salePriceDrop;
    private SingleDrop singleDrop;
    private MoreDrop moreDrop;

    private NewEstListApi newEstListApi;
    private LocationClient locationClient;
    protected boolean needLocation;//是否需要定位

    @Override
    protected int setLayoutId() {
        return R.layout.activity_new_est_nearby;
    }

    @Override
    protected void findViews() {
        setUniversalToolbar(R.string.title_new_est_of_nearby);
        dropDownView = (DropDownView) findViewById(R.id.dropDownView);
        newEstListFragment = (NewEstListFragment) getSupportFragmentManager().findFragmentById(R.id.newEstListFragment);
    }

    @Override
    protected void initViews() {
        newEstListFragment.setRefreshListener(new RefreshListener() {
            @Override
            public void down() {
                newEstListApi.setStartIndex(0);
                if (needLocation) {
                    startLocation();
                } else {
                    refreshList();
                }
            }

            @Override
            public void up(int count) {
                newEstListApi.setStartIndex(count);
                refreshList();
            }
        });
        dropDownView.setDropCompleteListener(new DropCompleteListener() {
            @Override
            public void complete(int position, boolean fromMore, int type, DropBo... dropBos) {
                final int size = dropBos == null ? 0 : dropBos.length;
                if (fromMore) {
                    newEstListApi.resetOther();
                    if (size == 0) {
                        downRefresh(false);
                    } else {
                        StringBuilder tags = new StringBuilder();
                        for (DropBo dropBo : dropBos) {
                            final int innerType = dropBo.getType();
                            switch (innerType) {
                                case 100://排序
                                    newEstListApi.setSortBy(dropBo.getValue());
                                    break;
                                case 110://物业类型
                                    newEstListApi.setEstType("");
                                    if (!TextUtils.isEmpty(dropBo.getValue())) {
                                        newEstListApi.setEstType(dropBo.getValue());
                                    }
                                    break;
                                case 130://开盘时间
                                    if (dropBo.getValue() != null &&
                                            dropBo.getValue().contains(",")) {
                                        String[] op = dropBo.getValue().split(",");
                                        Calendar calendar = Calendar.getInstance();
                                        calendar.setTime(new Date());
                                        int begin = Integer.parseInt(op[0]);
                                        int end = Integer.parseInt(op[1]);
                                        if (begin != 0) {
                                            calendar.add(Calendar.MONTH, begin);
                                        }
                                        newEstListApi.setOpDateBegin(DateUtil.format(begin == 0 ?
                                                        System.currentTimeMillis() : calendar.getTimeInMillis(),
                                                DateUtil.FORMAT2));
                                        if (end != 0) {
                                            calendar.add(Calendar.MONTH, end);
                                        }
                                        newEstListApi.setOpDateEnd(DateUtil.format(end == 0 ?
                                                        System.currentTimeMillis() : calendar.getTimeInMillis(),
                                                DateUtil.FORMAT2));
                                    }
                                    break;
                                case 80://特色
                                    tags.append(dropBo.getValue()).append(",");
                                    break;
                                default:
                                    break;
                            }
                        }
                        if (tags.toString().contains(",")) {
                            tags.deleteCharAt(tags.length() - 1);
                        }
                        newEstListApi.setTags(tags.toString());
                        downRefresh(false);
                    }
                } else {
                    switch (type) {
                        case 10://区域
                            newEstListApi.reset();
                            if (size == 1) {
                                if (DropUtil.compareValue(dropBos[0])) {
                                    resetTab(position);
                                } else {
                                    newEstListApi.setDistrictId(dropBos[0].getValue());
                                    setTab(position, dropBos[0].getText());
                                }
                                downRefresh(false);
                            } else if (size == 2) {
                                newEstListApi.setDistrictId(dropBos[0].getValue());
                                if (DropUtil.compareValue(dropBos[1])) {
                                    setTab(position, dropBos[0].getText());
                                } else {
                                    newEstListApi.setgScopeId(dropBos[1].getValue());
                                    setTab(position, dropBos[1].getText());
                                }
                                downRefresh(false);
                            }
                            break;
                        case 11://附近
                            downRefresh(true);
                            break;
                        case 30://均价
                            if (size == 1) {
                                String value = dropBos[0].getValue();
                                if (TextUtils.isEmpty(value)) {
                                    newEstListApi.setMinAveragePrice("");
                                    newEstListApi.setMaxAveragePrice("");
                                    resetTab(position);
                                    downRefresh(false);
                                } else if (value.contains(",")) {
                                    String[] values = value.split(",");
                                    newEstListApi.setMinAveragePrice(values[0]);
                                    newEstListApi.setMaxAveragePrice(values[1]);
                                    setTab(position, dropBos[0].getText());
                                    downRefresh(false);
                                }
                            } else if (size == 2) {
                                newEstListApi.setMinAveragePrice(dropBos[0].getValue());
                                newEstListApi.setMaxAveragePrice(dropBos[1].getValue());
                                setTab(position, DropUtil.customPrice(dropBos[0], dropBos[1]));
                                downRefresh(false);
                            }
                            break;
                        case 40://户型
                            newEstListApi.setRoomCnt("");
                            newEstListApi.setGtRoomCnt("");
                            if (size == 1) {
                                if (dropBos[0].getValue() != null &&
                                        dropBos[0].getValue().contains(",")) {
                                    String[] rooms = dropBos[0].getValue().split(",");
                                    if (rooms[0].equals(rooms[1])) {
                                        newEstListApi.setRoomCnt(rooms[0]);
                                        newEstListApi.setGtRoomCnt("0");
                                    } else {
                                        newEstListApi.setRoomCnt(rooms[0]);
                                        newEstListApi.setGtRoomCnt("1");
                                    }
                                }
                                setTab(position, dropBos[0].getText());
                                downRefresh(false);
                            }
                            break;
                        default:
                            break;
                    }
                }
            }
        });
        dropDownView.initTabs(R.array.newEstRecommend);
        doubleDrop = new DoubleDrop(dropDownView, this);
        salePriceDrop = new SalePriceDrop(dropDownView, this);
        singleDrop = new SingleDrop(dropDownView, this);
        moreDrop = new MoreDrop(dropDownView, this);
        dropDownView.addDrops(doubleDrop, salePriceDrop, singleDrop, moreDrop);

        Observable
                .combineLatest(RxDataBase
                                .getNewEstRegion()
                                .subscribeOn(Schedulers.io()),
                        RxDataBase.nearby(),
                        new Func2<ArrayList<DropBo>, DropBo, ArrayList<DropBo>>() {
                            @Override
                            public ArrayList<DropBo> call(ArrayList<DropBo> dropBos, DropBo dropBo) {
                                ArrayList<DropBo> temp = new ArrayList<>();
                                DropBo dropBo2 = new DropBo(10);
                                dropBo2.setText(CommonConstant.DROP_TEXT_NO_LIMITED);
                                dropBo2.setValue(CommonConstant.DROP_VALUE_NULL);
                                temp.add(dropBo2);
                                temp.addAll(dropBos);
                                if (AppConstant.NearbyEnable) {
                                    temp.add(dropBo);
                                }
                                return temp;
                            }
                        })
                .compose(this.<ArrayList<DropBo>>bindUntilEvent(ActivityEvent.DESTROY))
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<ArrayList<DropBo>>() {
                    @Override
                    public void call(ArrayList<DropBo> dropBos) {
                        doubleDrop.init(dropBos);
                    }
                });
        RxDataBase
                .getSearchData("NewHousePriceN")
                .map(new NewEstSearchDataFunc1(30))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .compose(this.<ArrayList<DropBo>>bindUntilEvent(ActivityEvent.DESTROY))
                .subscribe(new Action1<ArrayList<DropBo>>() {
                    @Override
                    public void call(ArrayList<DropBo> dropBos) {
                        salePriceDrop.init(dropBos);
                    }
                });
        RxDataBase
                .getSearchData("Room")
                .map(new NewEstSearchDataFunc1(40))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .compose(this.<ArrayList<DropBo>>bindUntilEvent(ActivityEvent.DESTROY))
                .subscribe(new Action1<ArrayList<DropBo>>() {
                    @Override
                    public void call(ArrayList<DropBo> dropBos) {
                        singleDrop.init(dropBos);
                    }
                });

        Observable
                .combineLatest(
                        RxDataBase.getSearchData("NewPropOrderBy").map(new NewEstSearchDataFunc1(100)),
                        RxDataBase.getSearchData("NewEstType").map(new NewEstSearchDataFunc1(110, true)),
                        RxDataBase.getSearchData("NewPropOpDate").map(new NewEstSearchDataFunc1(130)),
                        RxDataBase.getSearchData("NewPropFeatures").map(new NewEstSearchDataFunc1(80)),
                        new Func4<ArrayList<DropBo>, ArrayList<DropBo>, ArrayList<DropBo>, ArrayList<DropBo>,
                                ArrayList<DropBo>>() {
                            @Override
                            public ArrayList<DropBo> call(ArrayList<DropBo> dropBos, ArrayList<DropBo> dropBos2,
                                                          ArrayList<DropBo> dropBos3, ArrayList<DropBo> dropBos4) {
                                final ArrayList<DropBo> list = new ArrayList<>();
                                DropBo dropBo;
                                if (dropBos.size() > 0) {
                                    dropBo = new DropBo(100);
                                    dropBo.setText("排序");
                                    dropBo.setValue(CommonConstant.DROP_VALUE_NULL);
                                    dropBo.setChildrenList(dropBos);
                                    list.add(dropBo);
                                }
                                if (dropBos3.size() > 0) {
                                    dropBo = new DropBo(130);
                                    dropBo.setText("物业类型");
                                    dropBo.setValue(CommonConstant.DROP_VALUE_NULL);
                                    dropBo.setChildrenList(dropBos2);
                                    list.add(dropBo);
                                }
                                if (dropBos3.size() > 0) {
                                    dropBo = new DropBo(130);
                                    dropBo.setText("开盘时间");
                                    dropBo.setValue(CommonConstant.DROP_VALUE_NULL);
                                    dropBo.setChildrenList(dropBos2);
                                    list.add(dropBo);
                                }
                                if (dropBos4.size() > 0) {
                                    dropBo = new DropBo(80);
                                    dropBo.setText("特色");
                                    dropBo.setSelected(true);
                                    dropBo.setValue(CommonConstant.DROP_VALUE_NULL);
                                    dropBo.setChildrenList(dropBos3);
                                    list.add(dropBo);
                                }
                                return list;
                            }
                        })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .compose(this.<ArrayList<DropBo>>bindUntilEvent(ActivityEvent.DESTROY))
                .subscribe(new Action1<ArrayList<DropBo>>() {
                    @Override
                    public void call(ArrayList<DropBo> dropBos) {
                        moreDrop.init(dropBos);
                    }
                });

        newEstListApi = new NewEstListApi(NewEstListActivity.class, NewEstListRo.class, new IResponseListener<NewEstListRo>() {
            @Override
            public void onResponse(NewEstListRo newEstListRo) {
                newEstListFragment.stopRefresh(newEstListRo.getNewEstDoArrayList());
                if (newEstListApi.getStartIndex() == 0) {
                    snack(newEstListRo.getTotal() == 0 ?
                            getString(R.string.snack_new_est_nothing) :
                            String.format(Locale.CHINA, getString(R.string.snack_new_est), newEstListRo.getTotal()));
                }
            }

            @Override
            public void onErrorResponse(VolleyError error) {
                newEstListFragment.refreshError();
                netWorkUnable();
            }
        });

        double avgPrice = getIntent().getDoubleExtra(ExtraConstant.Price, 0);
        if (avgPrice > 0) {
            newEstListApi.setMinAveragePrice(String.format(Locale.CHINA, "%.0f", avgPrice * 0.9));
            newEstListApi.setMaxAveragePrice(String.format(Locale.CHINA, "%.0f", avgPrice * 1.1));
            LatLng latLng = getIntent().getParcelableExtra(ExtraConstant.LatLng);
            if (latLng != null &&
                    latLng.latitude != 0 &&
                    latLng.longitude != 0) {
                newEstListApi.setLatLng(latLng);
                newEstListApi.setSortBy("2");
            }
            newEstListFragment.setLocation(latLng);
            salePriceDrop.setMaxAndMin(String.format(Locale.CHINA, "%.1f", avgPrice * 1.1 / 10000),
                    String.format(Locale.CHINA, "%.1f", avgPrice * 0.9 / 10000));
            if (avgPrice * 0.9 > 10000) {
                setTab(1, String.format(Locale.CHINA, "%s-%s",
                        String.format(Locale.CHINA, "%.1f", avgPrice * 0.9 / 10000),
                        String.format(Locale.CHINA, "%.1f万", avgPrice * 1.1 / 10000)));
            } else if (avgPrice * 1.1 < 10000) {
                setTab(1, String.format(Locale.CHINA, "%s-%s",
                        String.format(Locale.CHINA, "%.0f", avgPrice),
                        String.format(Locale.CHINA, "%.1f元", avgPrice * 1.1)));
            } else {
                setTab(1, String.format(Locale.CHINA, "%s-%s",
                        String.format(Locale.CHINA, "%.0f元", avgPrice),
                        String.format(Locale.CHINA, "%.1f万", avgPrice * 1.1 / 10000)));
            }
        }

        locationClient = MyLocation.getLocationClient();
        RxMap.location(locationClient, false)
                .compose(this.<BDLocation>bindUntilEvent(ActivityEvent.DESTROY))
                .subscribe(new Action1<BDLocation>() {
                    @Override
                    public void call(BDLocation bdLocation) {
                        locationInfo(bdLocation);
                    }
                });
    }

    private void downRefresh(boolean needLocation) {
        this.needLocation = needLocation;
        newEstListFragment.startRefresh();
    }

    private void refreshList() {
        newEstListApi.startRequest();
    }

    /**
     * 开始定位
     */
    private void startLocation() {
        locationClient.start();
    }

    /**
     * 定位信息
     */
    protected void locationInfo(BDLocation bdLocation) {
        switch (bdLocation.getLocType()) {
            case 61:
            case 161:
                LatLng latLng = new LatLng(bdLocation.getLatitude(), bdLocation.getLongitude());
                newEstListApi.setLatLng(latLng);
                refreshList();
                break;
            default:
                newEstListApi.setLatLng(null);
                newEstListFragment.setLocation(null);
                break;
        }
    }

    private void resetTab(int position) {
        dropDownView.resetTab(position);
    }

    private void setTab(int position, String tab) {
        dropDownView.setTab(position, tab);
    }
}
